//
//  ViewController.swift
//  AppTest
//
//  Created by lete on 2020/7/16.
//  Copyright © 2020 lete. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {
    
    
    var filePath: URL!
    var documentVC:UIDocumentInteractionController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        
        
        filePath = URL.init(string: FilePathUtils.documentsDirectoryPath())?.appendingPathComponent("mytest.txt")
        
        let op =  FileUtils.createFile(filePath: filePath.path)
        print("----->>>>  \(op)")
        let arr = FileUtils.getFilePathList(folderPath: FilePathUtils.documentsDirectoryPath())
        print("==================")
            print(FilePathUtils.documentsDirectoryPath())
        print("==================")
        print(arr)
        print("==================")
    }
    
    @IBAction func share(_ sender: Any) {
        let url = URL.init(fileURLWithPath: filePath.path)
        let topVC = Utils.topviewController()
        documentVC = UIDocumentInteractionController(url: url)
        //        documentVC.url = url
        documentVC.delegate = self
        documentVC.presentOpenInMenu(from: CGRect.zero, in: (topVC?.view)!, animated: true)
        
        
    }
    
    func documentInteractionController(_ controller: UIDocumentInteractionController, willBeginSendingToApplication application: String?) {
        
    }
    
    func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) {
        
    }
    
    func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
        
    }
    
    
}



class Utils: NSObject {
    
    static func topviewController() -> UIViewController? {
        
        var aRoot = UIApplication.shared.keyWindow?.rootViewController
        
        while aRoot?.presentedViewController != nil {
            aRoot = aRoot?.presentedViewController
            
            if aRoot is UINavigationController {
                aRoot = (aRoot as? UINavigationController)?.visibleViewController
            } else if aRoot is UITabBarController {
                aRoot = (aRoot as? UITabBarController)?.selectedViewController
            }
        }
        
        return aRoot
    }
}
